/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package canteen.sys.view;

import canteen.sys.model.entity.DesignationMaster;
import canteen.sys.model.generic.HibernateDAOFactory;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;

/**
 *
 * @author TNT
 */
public class DesignatoinEntry extends javax.swing.JInternalFrame implements ActionView<DesignationMaster> {

    HibernateDAOFactory hibernateDAOFactory = HibernateDAOFactory.getInstance();
    DefaultTableModel modelTable;

    /**
     * Creates new form DesignatoinEntry
     */
    public DesignatoinEntry() {
        initComponents();
        modelTable = (DefaultTableModel) tableDesignation.getModel();
        List<DesignationMaster> listDesign = hibernateDAOFactory.getDesignationMasterDAO().findAll();
        showList(listDesign);
        listenerTableModel();
        listSelectionListener();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        btsave = new javax.swing.JButton();
        btdelete = new javax.swing.JButton();
        btcancel = new javax.swing.JButton();
        txtDesignID = new javax.swing.JTextField();
        txtDesignName = new javax.swing.JTextField();
        rbStatus = new javax.swing.JRadioButton();
        jLabel3 = new javax.swing.JLabel();
        jLayeredPane2 = new javax.swing.JLayeredPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableDesignation = new javax.swing.JTable();

        setClosable(true);
        setTitle("Designation Entry");

        jLayeredPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Box"));
        jLayeredPane1.setToolTipText("");

        jLabel1.setText("Designation ID");
        jLabel1.setBounds(10, 30, 130, 14);
        jLayeredPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel2.setText("Designation Name");
        jLabel2.setBounds(10, 70, 130, 14);
        jLayeredPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        btsave.setText("Save");
        btsave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btsaveActionPerformed(evt);
            }
        });
        btsave.setBounds(10, 140, 80, 23);
        jLayeredPane1.add(btsave, javax.swing.JLayeredPane.DEFAULT_LAYER);

        btdelete.setText("Delete");
        btdelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btdeleteActionPerformed(evt);
            }
        });
        btdelete.setBounds(110, 140, 80, 23);
        jLayeredPane1.add(btdelete, javax.swing.JLayeredPane.DEFAULT_LAYER);

        btcancel.setText("Cancel");
        btcancel.setEnabled(false);
        btcancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btcancelActionPerformed(evt);
            }
        });
        btcancel.setBounds(210, 140, 80, 23);
        jLayeredPane1.add(btcancel, javax.swing.JLayeredPane.DEFAULT_LAYER);

        txtDesignID.setEnabled(false);
        txtDesignID.setBounds(150, 30, 190, 20);
        jLayeredPane1.add(txtDesignID, javax.swing.JLayeredPane.DEFAULT_LAYER);
        txtDesignName.setBounds(150, 70, 190, 20);
        jLayeredPane1.add(txtDesignName, javax.swing.JLayeredPane.DEFAULT_LAYER);

        rbStatus.setSelected(true);
        rbStatus.setBounds(150, 100, 21, 21);
        jLayeredPane1.add(rbStatus, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel3.setText("Status");
        jLabel3.setBounds(10, 100, 90, 14);
        jLayeredPane1.add(jLabel3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLayeredPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(""), "Click on Record to Delete or Edit"));

        tableDesignation.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null},
                {null, null, null},
                {null, null, null},
                {null, null, null}
            },
            new String [] {
                "ID", "Name", "Status"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tableDesignation);
        tableDesignation.getColumnModel().getColumn(0).setMinWidth(40);
        tableDesignation.getColumnModel().getColumn(0).setMaxWidth(50);
        tableDesignation.getColumnModel().getColumn(2).setMinWidth(50);
        tableDesignation.getColumnModel().getColumn(2).setPreferredWidth(100);
        tableDesignation.getColumnModel().getColumn(2).setMaxWidth(100);

        jScrollPane1.setBounds(10, 20, 340, 340);
        jLayeredPane2.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jLayeredPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 359, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLayeredPane2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 359, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jLayeredPane2)
            .add(layout.createSequentialGroup()
                .add(jLayeredPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 172, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(0, 239, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btsaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btsaveActionPerformed
        // TODO add your handling code here:
        try {
            DesignationMaster designationMaster = new DesignationMaster();
            if (btsave.getText().equals("Save")) {
                designationMaster.setDesignationName(txtDesignName.getText());
                designationMaster.setStatus(rbStatus.isSelected());
                validInsertDesignation(designationMaster);
            } else {
                designationMaster.setDesgId(Integer.parseInt(txtDesignID.getText()));
                designationMaster.setDesignationName(txtDesignName.getText());
                designationMaster.setStatus(rbStatus.isSelected());
                validInsertDesignation(designationMaster);
                btsave.setText("Save");
                btcancel.setEnabled(false);
            }
            this.txtDesignName.requestFocus();
        } catch (HibernateException ex) {
            JOptionPane.showMessageDialog(this, "Add new DepartmentEntry Fail!\n Error: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btsaveActionPerformed

    private void btdeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btdeleteActionPerformed
        // TODO add your handling code here:
        int indexRow = tableDesignation.getSelectedRow();
        if (indexRow != -1) {
            try {
                if (modelTable.getRowCount() > 1) {
                    hibernateDAOFactory.getDesignationMasterDAO().makeTransient(getObject(indexRow));
                    deleteRow(indexRow);
                }
            } catch (HibernateException ex) {
                JOptionPane.showMessageDialog(this, "Can't delete Department\nError: " + ex.getMessage());
            }
        } else {
            JOptionPane.showMessageDialog(this, "No row selected!", "Warning", JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_btdeleteActionPerformed

    private void btcancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btcancelActionPerformed
        // TODO add your handling code here:
        //        DepartmentMaster departmentMaster = new DepartmentMaster();
        //        departmentMaster.setDepartmentName("TNTuyen");
        //        departmentMaster.setStatus(false);
        //        updateRow(departmentMaster, 2);
        btsave.setText("Save");
        btcancel.setEnabled(false);
//        this.dispose();
    }//GEN-LAST:event_btcancelActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btcancel;
    private javax.swing.JButton btdelete;
    private javax.swing.JButton btsave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JLayeredPane jLayeredPane2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rbStatus;
    private javax.swing.JTable tableDesignation;
    private javax.swing.JTextField txtDesignID;
    private javax.swing.JTextField txtDesignName;
    // End of variables declaration//GEN-END:variables

    public final void listenerTableModel() {
        modelTable.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                if (e.getType() == TableModelEvent.DELETE) {
                    JOptionPane.showMessageDialog(null, "Delete Success!");
                }
                if (e.getType() == TableModelEvent.INSERT) {
                    JOptionPane.showMessageDialog(null, "Add new Department Success!");
                } else if (e.getType() == TableModelEvent.UPDATE && e.getColumn() == 2) {
                    JOptionPane.showMessageDialog(null, "Update Desination Success!");
                }
            }
        });
    }

    public final void listSelectionListener() {
        tableDesignation.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int rowSelected = tableDesignation.getSelectedRow();
                showDetail(getObject(rowSelected));
                btsave.setText("Update");
                btcancel.setEnabled(true);
            }
        });
    }

    @Override
    public void showDetail(DesignationMaster designation) {
        txtDesignID.setText(designation.getDesgId() + "");
        txtDesignName.setText(designation.getDesignationName());
        rbStatus.setSelected(designation.isStatus());
    }

    @Override
    public void deleteRow(int index) {

        if (modelTable.getRowCount() > 0) {
            if (index > 0) {
                tableDesignation.setRowSelectionInterval(index - 1, index - 1);
                modelTable.removeRow(index);
            } else {
                tableDesignation.setRowSelectionInterval(index + 1, index + 1);
                modelTable.removeRow(0);
            }
        } else {
            JOptionPane.showMessageDialog(this, "There is no row to delete!", "Warning!", JOptionPane.WARNING_MESSAGE);
        }
    }

    @Override
    public DesignationMaster getObject(int index) {
        DesignationMaster designationMaster = new DesignationMaster();
        boolean status = false;
        designationMaster.setDesgId(Integer.parseInt(modelTable.getValueAt(index, 0).toString()));
        designationMaster.setDesignationName(modelTable.getValueAt(index, 1).toString());
        if (modelTable.getValueAt(index, 2).equals("enable")) {
            status = true;
        }
        designationMaster.setStatus(status);
        return designationMaster;
    }

    @Override
    public void updateRow(DesignationMaster row, int index) {
        modelTable.setValueAt(row.getDesignationName(), index, 1);
        if (row.isStatus()) {
            modelTable.setValueAt("enable", index, 2);
        } else {
            modelTable.setValueAt("disable", index, 2);
        }
    }

    @Override
    public void addRow(DesignationMaster row, boolean posion) {
        String status = "disable";
        if (row.isStatus()) {
            status = "enable";
        }
        if (posion) {
            modelTable.insertRow(0, new Object[]{row.getDesgId() + "", row.getDesignationName() + "", status});
        } else {
            modelTable.insertRow(tableDesignation.getRowCount(), new Object[]{row.getDesgId() + "", row.getDesignationName() + "", status});
        }
    }

    @Override
    public final void showList(List<DesignationMaster> list) {
        String status;
        for (int i = 0; i < 4; i++) {
            modelTable.removeRow(0);
        }
        for (DesignationMaster item : list) {
            if (item.isStatus()) {
                status = "enable";
            } else {
                status = "disable";
            }
            modelTable.insertRow(0, new Object[]{item.getDesgId(), item.getDesignationName(), status});
        }

        //setModelTable(model);
    }

    @Override
    public boolean validObject(DesignationMaster object) {
        if (object.getDesignationName().equals("") || object.getDesignationName() == null) {
            JOptionPane.showMessageDialog(this, "Designation Name must input!");
            return false;
        }
        return true;
    }

    private void validInsertDesignation(DesignationMaster designationMaster) {
        if (validObject(designationMaster)) {
            DesignationMaster departmentResult = hibernateDAOFactory.getDesignationMasterDAO().makePersistent(designationMaster);
            showDetail(departmentResult);
            if (btsave.getText().equals("Save")) {
                addRow(designationMaster, true);
            } else {
                updateRow(designationMaster, tableDesignation.getSelectedRow());
            }
        }
    }

    @Override
    public void setObject(DesignationMaster object) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
